package com.wei.lawyer.ui.activity;

import android.os.Bundle;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.wei.lawyer.App;
import com.wei.lawyer.R;
import com.wei.lawyer.model.BookBean;
import com.wei.lawyer.net.presenter.HomePresenter;
import com.wei.lawyer.ui.adapter.BaseDelegateAdapter;
import com.wei.lawyer.ui.adapter.BaseViewHolder;
import com.wei.lawyer.utils.RxUtils;

import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;

/**
 * 作者：赵若位
 * 时间：2018/11/14 14:41
 * 邮箱：1070138445@qq.com
 * 功能：文书服务
 */
public class BookActivity extends BaseActivity<HomePresenter>
{
    @Bind(R.id.recyclerView)
    RecyclerView mRecyclerView;
    /*服务类型，合同类型，参考价格*/
    private TextView mTvService, mTvContract, mTvPrice;

    private DelegateAdapter mAdapter;

    private BaseDelegateAdapter mProcessAdapter, mPriceAdapter;

    /*服务类型，合同类型*/
    private OptionsPickerView mServicePickView, mContractPickView;
    private List<String> mServiceData;
    private BookBean mData;

    @Override
    protected int getLayoutResource()
    {
        return R.layout.activity_book;
    }

    @Override
    protected void setStatusBarColor()
    {

    }

    @Override
    protected HomePresenter createPresenter()
    {
        return new HomePresenter(this, this);
    }

    @Override
    protected void initView(Bundle savedInstanceState)
    {
        super.initView(savedInstanceState);
        setLeftBack();
        setTitle(getString(R.string.tv_home_book));

        VirtualLayoutManager manager = new VirtualLayoutManager(mActivity);
        manager.setInitialPrefetchItemCount(3);
        mRecyclerView.setLayoutManager(manager);
        //关闭动效提升效率
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mRecyclerView.setItemViewCacheSize(3);

        mAdapter = new DelegateAdapter(manager);
        mRecyclerView.setAdapter(mAdapter);
        //初始化适配器
        initAdapter();
    }

    /*初始化适配器*/
    private void initAdapter()
    {
        //流程
        mProcessAdapter = new BaseDelegateAdapter<String>(this, R.layout.layout_book_process)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, String s)
            {
                mTvService = holder.getView(R.id.tv_service);
                mTvContract = holder.getView(R.id.tv_contract);
                mTvPrice = holder.getView(R.id.tv_price);
                holder.setOnClickListener(R.id.tv_service, new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        //服务类型选择器
                        initServicePickView();
                    }
                }).setOnClickListener(R.id.tv_contract, new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        //合同类型
                        if (mContractPickView != null)
                        {
                            mContractPickView.show();
                        }else
                        {
                            alert(getString(R.string.alert_get_data_error));
                            initData();
                        }
                    }
                });

                //服务需求字数监听
                final EditText descript = holder.getView(R.id.et_descript);
                final TextView count = holder.getView(R.id.tv_count);
                descript.addTextChangedListener(new TextWatcher()
                {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after)
                    {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count)
                    {

                    }

                    @Override
                    public void afterTextChanged(Editable s)
                    {
                        StringBuilder builder = new StringBuilder();
                        builder.append(descript.getText().toString().length())
                                .append("/100");
                        count.setText(builder);
                    }
                });
            }
        };
        mAdapter.addAdapter(mProcessAdapter);
        mProcessAdapter.setData("");

        //支付方式
        mPriceAdapter = new BaseDelegateAdapter<BookBean>(this, R.layout.layout_book_pay_type)
        {
            //定制说明是否显示
            private boolean isVisible = true;

            @Override
            public void convert(final BaseViewHolder holder, int position, BookBean data)
            {
                StringBuilder builder = new StringBuilder();
                builder.append(getString(R.string.tv_money))
                        .append(data.getPrice()/100);
                holder.setText(builder, R.id.tv_price)
                        .setText(data.getContent(), R.id.tv_custom_descript)
                        .setVisible(R.id.tv_custom_descript, isVisible)
                        .setImageResource(isVisible ? R.mipmap.search_more_1 : R.mipmap.search_more_2, R.id.img_custom)
                        .setOnClickListener(R.id.img_custom, new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                isVisible = !isVisible;
                                notifyDataSetChanged();
                            }
                        }).setOnClickListener(R.id.img_wen, new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        isVisible = !isVisible;
                        notifyDataSetChanged();
                    }
                });
                setUrgentUi((TextView) holder.getView(R.id.tv_pay_urgent_descript_1));
            }

            //异步设置平台加急UI样式
            private void setUrgentUi(final TextView view)
            {
                if (view != null)
                {
                    Observable.create(new ObservableOnSubscribe<SpannableString>()
                    {
                        @Override
                        public void subscribe(ObservableEmitter<SpannableString> e) throws Exception
                        {
                            String price = String.valueOf(App.mConfig != null ? App.mConfig.getUrgentChatPrice() / 100 : 0);
                            String descript = getString(R.string.tv_urgent_descript_1).replace("Price", price);
                            SpannableString span = new SpannableString(descript);
                            ForegroundColorSpan title = new ForegroundColorSpan(getResources().getColor(R.color.textTitle));
                            span.setSpan(title, 0, descript.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
                            ForegroundColorSpan color = new ForegroundColorSpan(getResources().getColor(R.color.price));
                            span.setSpan(color, 2, 3 + price.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                            e.onNext(span);
                            e.onComplete();
                        }
                    }).compose(RxUtils.<SpannableString>rxObservableSchedlers())
                            .compose(mActivity.<SpannableString>bindUntilEvent(ActivityEvent.DESTROY))
                            .subscribe(new Consumer<SpannableString>()
                            {
                                @Override
                                public void accept(SpannableString span) throws Exception
                                {
                                    view.setText(span);
                                }
                            });
                }
            }
        };
        mAdapter.addAdapter(mPriceAdapter);
        mPriceAdapter.setData(new BookBean());
    }

    /*初始化服务类型选择器*/
    private void initServicePickView()
    {
        if (mServicePickView == null)
        {
            mServiceData = Arrays.asList(getResources().getStringArray(R.array.tv_book_service));
            mServicePickView = new OptionsPickerBuilder(this, new OnOptionsSelectListener()
            {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v)
                {
                    if (mServiceData != null && mTvService != null)
                    {
                        mTvService.setText(mServiceData.get(options1));
                    }
                }
            }).setSubmitText(getString(R.string.tv_submit))
                    .setCancelText(getString(R.string.tv_cancel)).build();
            mServicePickView.setPicker(mServiceData);
        }
        mServicePickView.show();
    }


    /*初始化合同类型选择器*/
    private void initContractPickView()
    {
        if (mData != null)
        {
            mContractPickView = new OptionsPickerBuilder(this, new OnOptionsSelectListener()
            {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v)
                {
                    if (mData != null && mTvContract != null
                            && mTvPrice != null)
                    {
                        List<BookBean.TypesBean> list = mData.getTypes();
                        mTvContract.setText(list.get(options1).getName());
                        mTvPrice.setText(getString(R.string.tv_money) + list.get(options1).getPrice());
                    }
                }
            }).setSubmitText(getString(R.string.tv_submit))
                    .setCancelText(getString(R.string.tv_cancel))
                    .build();
            mContractPickView.setPicker(mData.getTypes());
        }
    }


    @Override
    protected void initData()
    {
        super.initData();
        mPresenter.getBookData();
    }

    @OnClick({R.id.tv_ordered, R.id.tv_kefu, R.id.tv_action})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.tv_ordered://我的订单
                openActivity(OrderActivity.class, null);
                break;
            case R.id.tv_kefu://客服
                break;
            case R.id.tv_action://支付下单
                if (mTvService != null && mTvContract != null)
                {
                    String service = mTvService.getText().toString();
                    if (service.equals(getString(R.string.tv_please_check)))
                    {
                        alert(getString(R.string.alert_please_check_service));
                        return;
                    }

                    String contract = mTvContract.getText().toString();
                    if (contract.equals(getString(R.string.tv_please_check)))
                    {
                        alert(getString(R.string.alert_please_check_contract));
                        return;
                    }

                    alert(getString(R.string.alert_send_book_order_success));
                    doFinish(200);
                }
                break;
        }
    }


    @Override
    public void showData(Object o)
    {
        super.showData(o);
        if (o instanceof BookBean)
        {
            mData = (BookBean) o;
            initContractPickView();
            mPriceAdapter.setData(mData);
        }
    }
}
